package com.graduation.smartparkingplatform.Controller;

import com.github.pagehelper.PageInfo;
import com.graduation.smartparkingplatform.Pojo.Record;
import com.graduation.smartparkingplatform.Response.Response;
import com.graduation.smartparkingplatform.Response.ResponseUtils;
import com.graduation.smartparkingplatform.Service.RecordService;
import com.graduation.smartparkingplatform.Utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/record")
public class RecordController {

  @Autowired RecordService recordService;

  // 获取停车记录列表
  @GetMapping("/recordList")
  public Response getRecordList(
      @RequestParam(value = "page", defaultValue = "1") Integer page,
      @RequestParam(value = "count", defaultValue = "10") Integer count) {
    try {
      PageInfo<Record> getRecordList = recordService.getRecordList(page, count);
      return ResponseUtils.buildSuccess(getRecordList);
    } catch (Exception e) {
      return ResponseUtils.buildError(e);
    }
  }

  // 模糊搜索
  @GetMapping("/searchRecord")
  public Response searchRecord(
      @RequestParam(value = "page", defaultValue = "1") Integer page,
      @RequestParam(value = "count", defaultValue = "10") Integer count,
      @RequestParam(value = "carPlate", defaultValue = "null") String carPlate) {
    try {
      PageInfo<Record> searchList = recordService.searchRecord(page, count, carPlate);
      return ResponseUtils.buildSuccess(searchList);
    } catch (Exception e) {
      return ResponseUtils.buildError(e);
    }
  }

  // 删除停车记录
  @PostMapping("/deleteRecord")
  public Response deleteRecord(@RequestParam("RecordId") Integer RecordId) {
    Boolean delete = recordService.deleteRecord(RecordId);
    if (delete) {
      return ResponseUtils.buildSuccess("删除停车记录成功");
    }
    return ResponseUtils.buildError("删除停车记录失败");
  }

  // 导出停车记录Excel
  @RequestMapping("/exportRecordExcel")
  public void exportDistinguishExcel(HttpServletResponse response) {

    List<Record> recordList = recordService.getRecordListAll();

    // 获取当前时间
    Calendar calendar = Calendar.getInstance();
    // 定义时间格式化
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HH:mm:ss");
    String nowTime = formatter.format(calendar.getTime());

    // 导出操作
    ExcelUtils.exportExcel(
        recordList, "停车记录", "sheet1", Record.class, "RecordDATA" + nowTime + ".xls", response);
    log.info("exportRecordExcel");
  }
}
